package com.bw.house.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.house.common.ResponseResult;
import com.bw.house.entity.TbHouse;
import com.bw.house.service.ITbHouseService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 邢晋宁
 * @since 2020-09-04
 */
@RestController
@RequestMapping("house")
public class TbHouseController {

    @Value("${xjnfilePath}")
    private String filePath;


    @Autowired
    private ITbHouseService houseService;

    /**
     * @Description: 房源列表
     * @Author: 王文佳
     * @Date: 2020/9/4 16:10
     * @param currentPage:
     * @param pageSize:
     * @param house:
     * @return: com.bw.house.common.ResponseResult
     **/
    @PostMapping("/list/{currentPage}/{pageSize}")
    public ResponseResult list(@PathVariable("currentPage")int currentPage,
                               @PathVariable("pageSize")int pageSize,
                               @RequestBody TbHouse house){

        return houseService.listAll(currentPage,pageSize,house);
    }

    /**
     * @Description: 房东房源添加
     * @Author: 王文佳
     * @Date: 2020/9/4 16:22
     * @param house:
     * @return: com.bw.house.common.ResponseResult
     **/
    @PostMapping("/addHouse")
    public ResponseResult addHouse(@RequestBody TbHouse house){

        return houseService.addHouse(house);
    }

    /**
     * @Description: 房东修改房源
     * @Author: 王文佳
     * @Date: 2020/9/4 16:38
     * @param house:
     * @return: com.bw.house.common.ResponseResult
     **/
    @PostMapping("/updateHouse")
    public ResponseResult updateHouse(@RequestBody TbHouse house){

        return houseService.updateHouse(house);
    }

    /**
     * @Description: 房东删除房源
     * @Author: 王文佳
     * @Date: 2020/9/4 16:46
     * @param id:
     * @return: com.bw.house.common.ResponseResult
     **/
    @GetMapping("/deleteHouse/{id}")
    public ResponseResult deleteHouse(@PathVariable("id")long id){

        return houseService.deleteHouse(id);
    }

    /**
     * @Description: 房东查询房源信息
     * @Author: 王文佳
     * @Date: 2020/9/4 16:48
     * @param id:
     * @return: com.bw.house.common.ResponseResult
     **/
    @GetMapping("/getByHoueseId/{id}")
    public ResponseResult getByHoueseId(@PathVariable("id")long id){

        return houseService.getByHoueseId(id);
    }

    /**
     * @Description: 审核通过
     * @Author: 王文佳
     * @Date: 2020/9/4 19:56
     * @param id:
     * @param house:
     * @return: com.bw.house.common.ResponseResult
     **/
    @PostMapping("/updateStatus/{id}")
    public ResponseResult updateStatus(@PathVariable("id")long id,@RequestBody TbHouse house){

        return houseService.updateStatus(id,house);
    }

    /**
     * @Description: 中介修改定价
     * @Author: 王文佳
     * @Date: 2020/9/4 19:56
     * @param house:
     * @param house:
     * @return: com.bw.house.common.ResponseResult
     **/
    @PostMapping("/saveHouse")
    public ResponseResult saveHouse(@RequestBody TbHouse house){

        return houseService.saveHouse(house);
    }

	/*
     * @Description:C端房源列表
     * @return: com.bw.house.common.ResponseResult
     **/
    @GetMapping("getList")
    public ResponseResult getList(){
        ResponseResult result=ResponseResult.SUCCESS();

        try {
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("STATUS",1);
            queryWrapper.eq("NUM",1);
            List list = houseService.list(queryWrapper);
            result.setResult(list);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("查询失败");
        }
        return result;
    }

    @GetMapping("findById/{id}")
    public TbHouse findById(@PathVariable("id") Long id){
        TbHouse tbHouse = houseService.getById(id);
        return tbHouse;
    }

    @GetMapping("updateStatuss/{id}")
    public ResponseResult updatehouse(@PathVariable("id") Long id){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbHouse tbHouse = houseService.getById(id);
            tbHouse.setStatus(2);
            tbHouse.setNum(0);
            houseService.saveOrUpdate(tbHouse);
            result.setMessage("修改成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
            result.setMessage("修改失败");

        }

        return result;
    }

    /**
     * 文件下载接口
     */
    @GetMapping("download/{picture}")
    public void download(@PathVariable("picture") String picture, HttpServletResponse response) {

        if (null == picture) {
            return;
        }
        try {
            String bucketName = "chuang-ying";
            OSS ossClient =getOss();
            // <yourObjectName>从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = filePath+picture;
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            InputStream inputStream = ossObject.getObjectContent();

            byte[] b = new byte[1024];//定义每次读取输入流当中的多少字节
            int len;//记录每次读取字节流的位置

            while ((len = inputStream.read(b)) > 0) {            //将文件流写到响应输出流当中
                response.getOutputStream().write(b, 0, len);
            }

            // 关闭OSSClient。
            ossClient.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 商品图片上传接口
     */
    @PostMapping("upload")
    public ResponseResult upload(MultipartFile file) {
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            //1，获取文件后缀
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            //2，重新定义文件名
            String fileName = UUID.randomUUID() + ext;
            //3，将文件复制到对应服务器的路径下

            String bucketName = "chuang-ying";

            // 创建OSSClient实例。
            OSS ossClient =getOss();

            // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
            File cfile = new File(file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(), cfile);
            ossClient.putObject(bucketName,filePath+fileName , new FileInputStream(cfile));
            // 会在本地产生临时文件，用完后需要删除
            if (cfile.exists()) {
                cfile.delete();
            }
            // 关闭OSSClient。
            ossClient.shutdown();

            //4，将文件的存储路径返回给前端
            Map map = new HashMap();
            map.put("path", fileName);
            result.setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("上传失败:" + e.toString());
        }
        return result;
    }

    // 创建OSSClient实例
    public OSS getOss(){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI4G96XgvtFw4GLTmcQJ5v";
        String accessKeySecret = "SHfhQzADRPAH8bZobaFQLyRvx4mre9";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        return ossClient;
    }

}
